package vn.com.vega.music.utils;

import java.lang.ref.WeakReference;
import java.util.List;

import vn.com.vega.chacha.R;
import vn.com.vega.chacha.v2.ActivityBase;
import vn.com.vega.chacha.v2.Asynctask.AddSongToPlaylist;
import vn.com.vega.chacha.v2.Asynctask.AddSongToPlaylist.AddSongToPlaylistListener;
import vn.com.vega.chacha.v2.Asynctask.CreateNewPlaylist;
import vn.com.vega.chacha.v2.Asynctask.CreateNewPlaylist.CreatePlaylistListener;
import vn.com.vega.chacha.v2.Asynctask.DoSomthingListener;
import vn.com.vega.chacha.v2.Asynctask.LoadPlaylistCreateByUser;
import vn.com.vega.chacha.v2.Asynctask.LoadPlaylistCreateByUser.LoadUserPlaylistListener;
import vn.com.vega.music.clientserver.JsonPlaylist;
import vn.com.vega.music.objects.Playlist;
import vn.com.vega.music.objects.Song;
import vn.com.vega.music.player.ChaChaProgressDialog;
import vn.com.vega.music.view.adapter.SelectPlaylistToAddSongAdapter;
import vn.com.vega.music.view.custom.ChaChaDialog;
import android.content.Context;
import android.os.AsyncTask;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class PlaylistUtil {

	private static void showListPlaylist(List<Playlist> listPlaylist,
			final List<Song> songList, final ActivityBase act) {
		if (listPlaylist.size() == 0) {
			addSongToNewPlaylist(songList, act);
			return;
		}
		final ChaChaDialog addToPlaylistDialog = new ChaChaDialog(act, null);
		addToPlaylistDialog.setCancelable(true);
		LayoutInflater inflater = (LayoutInflater) act
				.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

		View contentOfDialog = inflater.inflate(
				R.layout.view_select_add_playlist_dialog, null);
		final ListView viewListPlaylist = (ListView) contentOfDialog
				.findViewById(R.id.lv_list_playlist);
		final TextView addToExistPlaylist = (TextView) contentOfDialog
				.findViewById(R.id.add_to_playlist_exists);
		TextView addNewPlaylist = (TextView) contentOfDialog
				.findViewById(R.id.tv_add_to_new_playlist);

		addToExistPlaylist.setText(act
				.getString(R.string.add_to_exist_playlist)
				+ " ("
				+ listPlaylist.size() + ")");
		final SelectPlaylistToAddSongAdapter adapter = new SelectPlaylistToAddSongAdapter(
				act, listPlaylist);
		viewListPlaylist.setAdapter(adapter);
		addToExistPlaylist.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				if (viewListPlaylist.isShown()) {
					viewListPlaylist.setVisibility(View.GONE);
					addToExistPlaylist
							.setCompoundDrawablesWithIntrinsicBounds(
									act.getResources()
											.getDrawable(
													R.drawable.ic_arrow_right_add_song_to_the_playlist),
									null, null, null);
				} else {
					viewListPlaylist.setVisibility(View.VISIBLE);
					addToExistPlaylist
					.setCompoundDrawablesWithIntrinsicBounds(
							act.getResources()
									.getDrawable(
											R.drawable.ic_arrow_add_song_to_the_playlist),
							null, null, null);
				}
			}
		});
		addNewPlaylist.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				addToPlaylistDialog.dismiss();
				addSongToNewPlaylist(songList, act);
			}
		});

		viewListPlaylist
				.setOnItemClickListener(new AdapterView.OnItemClickListener() {

					@Override
					public void onItemClick(AdapterView<?> arg0, View arg1,
							int arg2, long arg3) {
						// TODO Auto-generated method stub
						addToPlaylistDialog.dismiss();
						Playlist playlist = (Playlist) adapter.getItem(arg2);
						AddSongToPlaylistListener addListener = new AddSongToPlaylistListener() {

							@Override
							public void addSuccess() {
								// TODO Auto-generated method stub
								Toast.makeText(act,
										"Thêm bài hát vào playlist thành công",
										Toast.LENGTH_SHORT).show();
							}

							@Override
							public void addFail(String message) {
								// TODO Auto-generated method stub
								if (Util.checkStringIsemptyOrNull(message)) {
									Toast.makeText(
											act,
											"Thêm bài hát vào playlist thất bại!",
											Toast.LENGTH_SHORT).show();
								} else {
									Toast.makeText(act, message,
											Toast.LENGTH_SHORT).show();
								}

							}
						};
						AddSongToPlaylist addSongToPlaylist = new AddSongToPlaylist(
								act, songList, playlist, addListener);
						addSongToPlaylist.execute();
					}
				});

		addToPlaylistDialog.setContentView(contentOfDialog);
		addToPlaylistDialog.hideBottomView();
		addToPlaylistDialog.setTitle(act.getString(R.string.select_playlist));
		addToPlaylistDialog.show();
	}

	/**
	 * Add song to playlist user select
	 * 
	 * @param song
	 * @param ctx
	 */
	public static void addSongToPlaylist(final List<Song> song,
			final ActivityBase act) {
		final ChaChaProgressDialog progress = new ChaChaProgressDialog(act);
		LoadUserPlaylistListener loadListPlaylistListener = new LoadUserPlaylistListener() {

			@Override
			public void startLoadPlaylist() {
				// TODO Auto-generated method stub
				progress.setMessage("Đang tải danh sách playlist...");
				progress.show();
			}

			@Override
			public void loadPlaylistSuccess(
					List<Playlist> listUserCreatePlaylist) {
				// TODO Auto-generated method stub
				showListPlaylist(listUserCreatePlaylist, song, act);
			}

			@Override
			public void loadPlaylistError(String errorMessage) {
				// TODO Auto-generated method stub
				String mesage;
				if (Util.checkStringIsemptyOrNull(errorMessage)) {
					mesage = "Tải danh sách playlist không thành công!";
				} else {
					mesage = errorMessage;
				}
				Toast.makeText(act, mesage, Toast.LENGTH_SHORT).show();
			}

			@Override
			public void finishLoadPlaylist() {
				// TODO Auto-generated method stub
				progress.dismiss();
			}
		};

		LoadPlaylistCreateByUser loadListPlaylist = new LoadPlaylistCreateByUser(
				act, loadListPlaylistListener);
		loadListPlaylist.execute();
	}

	/**
	 * Add song to new Playlist
	 * 
	 * @param songList
	 * @param act
	 */
	public static void addSongToNewPlaylist(final List<Song> songList,
			final ActivityBase act) {
		CreatePlaylistListener createListener = new CreatePlaylistListener() {

			@Override
			public void startCreatePlaylist() {
				// TODO Auto-generated method stub

			}

			@Override
			public void finishCreatePlaylist() {
				// TODO Auto-generated method stub

			}

			@Override
			public void createPlaylistSuccess() {
				// TODO Auto-generated method stub
				addSongToPlaylist(songList, act);
			}

			@Override
			public void createPlaylistFail(String message) {
				// TODO Auto-generated method stub
				if (Util.checkStringIsemptyOrNull(message)) {
					Toast.makeText(act, "Tạo playlist thất bại!",
							Toast.LENGTH_SHORT).show();
				} else {
					Toast.makeText(act, message, Toast.LENGTH_SHORT).show();
				}
			}
		};

		createNewPlaylist(act, createListener);

	}

	public static void createNewPlaylist(final ActivityBase act,
			final CreatePlaylistListener listener) {
		final ChaChaDialog dialog = new ChaChaDialog(act, null);
		LayoutInflater inflater = (LayoutInflater) act
				.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

		View contentOfDialog = inflater.inflate(R.layout.view_add_new_playlist,
				null);
		final EditText playlistName = (EditText) contentOfDialog
				.findViewById(R.id.editText_playlist_name);
		final EditText playlistDes = (EditText) contentOfDialog
				.findViewById(R.id.editText_playlist_des);
		final Toast toast = Toast.makeText(act, "", Toast.LENGTH_SHORT);
		View.OnClickListener okClickListener = new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				String playlistNameStr = playlistName.getText().toString()
						.trim();
				if (Util.checkStringIsemptyOrNull(playlistNameStr)) {
					toast.setText("Bạn chưa nhập tên cho playlist!");
					toast.show();
					return;
				}
				final Playlist playlist = new Playlist();
				playlist.title = playlistNameStr;
				CreateNewPlaylist createNewPlaylist = new CreateNewPlaylist(
						act, playlist, listener);
				createNewPlaylist.execute();
				dialog.dismiss();
			}
		};

		dialog.setContentView(contentOfDialog);
		dialog.setTitle("Tạo playlist mới");
		dialog.addButton("Tạo mới", okClickListener);
		dialog.show();
	}

	public interface likeAndUnlikePlaylistListener {
		public void startDoLike();

		public void startDoUnlike();

		public void likeSuccess();

		public void likeFail(String message);

		public void unlikeSuccess();

		public void unlikeFail(String message);
	}

	static class LikeAndUnlikePlaylist extends AsyncTask<Void, Void, Void> {
		WeakReference<ActivityBase> activityRfc;
		likeAndUnlikePlaylistListener listener;
		boolean doLike = true;
		String errorMessageString = null;
		Playlist playlist;

		public LikeAndUnlikePlaylist(ActivityBase act,
				likeAndUnlikePlaylistListener listener, Playlist playlist,
				boolean doLike) {
			activityRfc = new WeakReference<ActivityBase>(act);
			this.listener = listener;
			this.playlist = playlist;
			this.doLike = doLike;
		}

		private boolean checkIsLive() {
			ActivityBase act = activityRfc.get();
			if (act == null || act.isDestroy) {
				return false;
			}
			return true;
		}

		@Override
		protected Void doInBackground(Void... params) {
			// TODO Auto-generated method stub
			if (!checkIsLive()) {
				return null;
			}
			if (playlist == null) {
				errorMessageString = "";
				return null;
			}
			if (doLike) {
				// Do like playlist
				JsonPlaylist jsonPlaylist = JsonPlaylist
						.likePlaylist(playlist.serverId);
				if (jsonPlaylist.isSuccess()) {
					// Like success
					errorMessageString = null;
					return null;
				} else {
					errorMessageString = jsonPlaylist.getErrorMessage();
				}
			} else {
				// Do unlike playlist
				JsonPlaylist jsonPlaylist = JsonPlaylist
						.unlikePlaylist(playlist.serverId);
				if (jsonPlaylist.isSuccess()) {
					// Unlike success
					errorMessageString = null;
					return null;
				} else {
					errorMessageString = jsonPlaylist.getErrorMessage();
				}
			}
			return null;
		}

		@Override
		protected void onPostExecute(Void result) {
			// TODO Auto-generated method stub
			if (isCancelled() || !checkIsLive()) {
				return;
			}
			if (listener != null) {
				if (doLike) {
					if (errorMessageString == null) {
						listener.likeSuccess();
						playlist.isFavorite = true;
					} else {
						listener.likeFail(errorMessageString);
					}
				} else {
					if (errorMessageString == null) {
						listener.unlikeSuccess();
						playlist.isFavorite = false;
					} else {
						listener.unlikeFail(errorMessageString);
					}
				}
			}
		}

		@Override
		protected void onPreExecute() {
			// TODO Auto-generated method stub
			if (!checkIsLive()) {
				return;
			}
			if (listener != null) {
				if (doLike) {
					listener.startDoLike();
				} else {
					listener.startDoUnlike();
				}
			}
		}

	}

	public static void doLikePlaylist(ActivityBase act, Playlist playlist,
			likeAndUnlikePlaylistListener listener) {
		LikeAndUnlikePlaylist likeAndUnlikePlaylist = new LikeAndUnlikePlaylist(
				act, listener, playlist, true);
		likeAndUnlikePlaylist.execute();
	}

	public static void doUnLikePlaylist(ActivityBase act, Playlist playlist,
			likeAndUnlikePlaylistListener listener) {
		LikeAndUnlikePlaylist likeAndUnlikePlaylist = new LikeAndUnlikePlaylist(
				act, listener, playlist, false);
		likeAndUnlikePlaylist.execute();
	}

	public static void sharePlaylist(Playlist playlist, ActivityBase act,
			SharePlaylistListener listenter) {
		SharePlaylist sharePlaylist = new SharePlaylist(act, playlist,
				listenter);
		sharePlaylist.execute();
	}

	public interface SharePlaylistListener {
		public void shareSuccess(Playlist playlist);

		public void shareFail(Playlist plalist, String errorMessage);
	}

	static class SharePlaylist extends AsyncTask<Void, Void, Void> {
		WeakReference<ActivityBase> activityRfc;
		Playlist playlist;
		SharePlaylistListener shareListener;
		String errorMessage = null;
		String shareMessage = "";

		public SharePlaylist(ActivityBase act, Playlist sharePlaylist,
				SharePlaylistListener listener) {
			activityRfc = new WeakReference<ActivityBase>(act);
			playlist = sharePlaylist;
			shareListener = listener;
		}

		private boolean checkIsLive() {
			ActivityBase act = activityRfc.get();
			if (act == null || act.isDestroy) {
				return false;
			} else {
				return true;
			}
		}

		@Override
		protected Void doInBackground(Void... params) {
			// TODO Auto-generated method stub
			if (!checkIsLive()) {
				return null;
			}
			if (playlist == null) {
				errorMessage = "";
				return null;
			}
			JsonPlaylist jsonPlaylist = JsonPlaylist
					.sharePlaylist(playlist.serverId);
			if (jsonPlaylist.isSuccess()) {
				shareMessage = jsonPlaylist.shareMsg + " - "
						+ jsonPlaylist.shareLink;
				errorMessage = null;
			} else {
				errorMessage = jsonPlaylist.getErrorMessage();
				if (errorMessage == null) {
					errorMessage = "";
				}
			}
			return null;
		}

		@Override
		protected void onPostExecute(Void result) {
			// TODO Auto-generated method stub
			if (!checkIsLive() || isCancelled()) {
				return;
			}
			if (errorMessage != null && shareListener != null) {
				shareListener.shareFail(playlist, errorMessage);
				return;
			}
			ActivityBase act = activityRfc.get();
			if (!Util.checkStringIsemptyOrNull(shareMessage)) {
				Util.share(shareMessage, act);
			}
		}
	}
}
